package com.cbtx.module_sp.ui.activity

import android.Manifest
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.os.Handler
import android.provider.Settings
import android.util.Log
import android.view.View
import android.widget.Toast
import androidx.lifecycle.Observer
import com.cbtx.module_sp.MyApplication
import com.cbtx.module_sp.R
import com.cbtx.module_sp.ui.activity.base.MyBaseVMActivity
import com.cbtx.module_sp.ui.vm.StartActivityVM
import com.tbruyelle.rxpermissions2.RxPermissions
import com.txcb.lib.base.utils.LoadingDialogUtil
import com.txcb.lib.base.utils.SharedPreferencesUtils
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.reactivex.functions.Consumer
import kotlinx.android.synthetic.main.sp_activity_start.*
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import java.util.concurrent.TimeUnit

class StartActivity : MyBaseVMActivity<StartActivityVM>() {

    private var dispose: Disposable? = null

    override fun getPresenterClazz(): Class<StartActivityVM> {
        return StartActivityVM::class.java
    }

    override fun getLayoutId(): Int {

        return R.layout.sp_activity_start
    }

    override fun initView(savedInstanceState: Bundle?) {
        mTvCode.text = "云屏编码:${MyApplication.mAndroidId}"

        //防止重复点击
//        addClickListener(mTvPersonal)
//        addClickListener(mTvCompany)

        mTouchLongView.setOnLongClickListener {
            toNetSet()
            return@setOnLongClickListener false
        }

        if (!Settings.canDrawOverlays(this)) {
            val intent = Intent(
                Settings.ACTION_MANAGE_OVERLAY_PERMISSION,
                Uri.parse("package:$packageName")
            )
            startActivityForResult(intent, REQUEST_OVERLAY)
        }


        //拍照要的权限
        val permission = arrayOf(
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.ACCESS_COARSE_LOCATION,
            Manifest.permission.READ_PHONE_STATE
        )

        RxPermissions(this@StartActivity)
            .request(*permission)
            .subscribe(Consumer<Boolean?> { aBoolean ->
                if (!aBoolean!!) {
                    Toast.makeText(this@StartActivity, "  权限不足", Toast.LENGTH_LONG).show()
                } else {
                    LoadingDialogUtil.showDialog(mActivity, "")
                    checkNet()
                }
            })


        mVM.loginDataResult.observe(this, Observer {
            if (it) {
                //获取数据后，允许进入首页
                dispose?.apply {
                    if (!this.isDisposed) {
                        this.dispose()
                    }
                }
                MainActivity.start(mActivity!!)
            }
            LoadingDialogUtil.closeDialog()
        })

        mVM.qrCodeBitmap.observe(this, Observer {
            iv_qr_code_display.setImageBitmap(it)
        })

        EventBus.getDefault().register(this)
//        startTime()
    }

    override fun onMyViewClick(view: View) {

    }

    val mHandlerTime = Handler()

    private fun startTime() {
        Log.e("TAG","startTime")
        mHandlerTime.postDelayed({
            checkNet()
        }, 1000 * 5)
    }

    var isNeedShowNetDialog = true

    private fun checkNet() {
        Log.e("TAG","checkNet")
        if (!isNetworkConnected(mActivity)) {
            if (isNeedShowNetDialog) {
                isNeedShowNetDialog = false
                showNoNet(true)
            }
            startTime()
        } else {
            if (SharedPreferencesUtils.loadBoolean("isBind")) {
                MainActivity.start(mActivity!!)
            } else {
                dispose = Observable.interval(0, 5, TimeUnit.SECONDS)
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe {
                        Log.e("TAG","登录页面上报")
                        mVM.requestLoginAuth()
                    }
            }
            showNoNet(false)
        }
    }

    override fun getData() {

    }

    override fun onDestroy() {
        super.onDestroy()
        mHandlerTime.removeCallbacksAndMessages(null)
        EventBus.getDefault().unregister(this)

    }

    override fun onBackPressed() {

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun closeNetDialog(closeNetDialog: String) {
        if ("closeNetDialog" == closeNetDialog) {
            checkNet()
        }
    }

}